document.addEventListener('DOMContentLoaded', function () {
    const typeSelector = document.getElementById('id_article_type');
    if (!typeSelector) {
        console.error('Type selector element not found');
        return;
    }

    // 假设元素是动态生成的，使用 MutationObserver 监听 DOM 变化
    const observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            if (mutation.type === 'childList') {
                toggleFields();
            }
        });
    });

    const config = { childList: true, subtree: true };
    observer.observe(document.body, config);

    function toggleFields() {
        const type = typeSelector.value;

        const mainImageField = document.querySelector('.field-image');
        if (mainImageField) {
            mainImageField.style.display = type === 'single' ? 'block' : 'none';
        } else {
            console.error('Main image field element not found');
        }

        const multiImageGroup = document.querySelector('#articleimage_set-group');
        if (multiImageGroup) {
            multiImageGroup.style.display = type === 'multi' ? 'block' : 'none';
        } else {
            console.error('Multi image group element not found');
        }

        const imageInput = document.querySelector('input[name="image"]');
        if (imageInput) {
            imageInput.required = type === 'single';
        } else {
            console.error('Image input element not found');
        }
    }

    typeSelector.addEventListener('change', toggleFields);
    toggleFields(); // 初始化状态
});
